package com.sparrow.common.util;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * 动态代理工具类
 */
public class DynamicProxyUtil {

    /**
     * 创建jdk动态代理
     * @param clazz 接口类
     * @param handler
     * @return
     */
    public static Object createJDKProxy(Class<?> clazz, InvocationHandler handler) {
        if (!clazz.isInterface()) {
            throw new RuntimeException(clazz + " 不是一个接口！");
        }
        return Proxy.newProxyInstance(
                clazz.getClassLoader(),
                new Class[]{clazz},
                handler
        );
    }

    /**
     * 创建cglib动态代理
     * @param clazz
     * @param methodInterceptor
     * @return
     */
    public static Object createCGLIBProxy(Class<?> clazz, MethodInterceptor methodInterceptor) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz); // 设置要代理的类
        enhancer.setCallback(methodInterceptor); // 设置拦截器
        return enhancer.create();
    }

}
